package com.fj.netty.future;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author fj
 * @date 2024/1/4 10:59
 */
public class TestFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.Jdk util concurrent Future
//        ExecutorService executorService = Executors.newFixedThreadPool(2);
//        Future<Integer> future = executorService.submit(() -> {
//            System.out.println("计算中...");
//            Thread.sleep(1000);
//            return 50;
//        });
//        System.out.println("计算完成:"+future.get());
        //2.Netty Future
//        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(2);
//        EventLoop eventLoop = nioEventLoopGroup.next();
//        Future<Integer> future = eventLoop.submit(() -> {
//            System.out.println("开始计算...");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            return 60;
//        });
//        System.out.println("计算完成:"+future.get());
//        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
//            @Override
//            public void operationComplete(Future<? super Integer> future) throws Exception {
//                System.out.println("计算完成监听："+future.getNow());
//            }
//        });
        //3.Netty Future
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(1);
        DefaultPromise defaultPromise = new DefaultPromise(nioEventLoopGroup.next());
        new Thread(()->{
            try {
                System.out.println("开始计算...");
                Random random = new Random();
                Thread.sleep(1000);
                if(random.nextBoolean()){
                    defaultPromise.setSuccess(100);
                }else{
                    throw new InterruptedException("aaa");
                }
            } catch (InterruptedException e) {
                defaultPromise.setFailure(e);
                throw new RuntimeException(e);
            }
        }).start();
        System.out.println(defaultPromise.getNow());
        System.out.println("计算完成:"+defaultPromise.get());
    }
}
